package com.yt.order.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.order.common.config.AlipayConfig;
import com.yt.order.models.bo.PayBO;
import com.yt.order.models.dto.WorkOrderInfoDTO;
import com.yt.order.models.service.IAlipayService;
import com.yt.order.models.service.IWorkOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@DubboService
public class AlipayServiceImpl implements IAlipayService {

    @Resource
    private AlipayConfig alipayConfig;

    @Resource
    private IWorkOrderInfoService workOrderInfoService;

    /**
     * 创建支付宝支付表单（返回HTML表单字符串，前端直接渲染）
     */
    @Override
    public Result<String> createPayOrder(PayBO payBO) {
        // 1. 验证参数
        if (payBO.getWorkOrderId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 2. 验证订单存在性
        WorkOrderInfoDTO order = workOrderInfoService.selectById(payBO.getWorkOrderId());
        if (order == null) {
            return new Result<>(CodeEnum.FAIL_ORDER_300000); // 假设订单不存在的枚举
        }

        // 3. 初始化支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                "json",
                "UTF-8",
                alipayConfig.getPublicKey(),
                "RSA2"
        );

        // 4. 构建支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(alipayConfig.getReturnUrl());
        request.setNotifyUrl(alipayConfig.getNotifyUrl());

        // 5. 组装订单参数（订单号、金额、标题等）
        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("id", payBO.getWorkOrderId());
        WorkOrderInfoDTO workOrderInfoDTO = workOrderInfoService.selectOne(wrapper);
        String outTradeNo = String.valueOf(payBO.getWorkOrderId()); // 用工单ID作为商户订单号
        String totalAmount = workOrderInfoDTO.getPrice().toString(); // 支付金额（元）
        String subject = "工单支付-" + outTradeNo; // 订单标题

        try {
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + outTradeNo + "\"," +
                    "\"total_amount\":\"" + totalAmount + "\"," +
                    "\"subject\":\"" + subject + "\"," +
                    "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                    "}");

            // 6. 调用支付宝接口生成支付表单
            String form = alipayClient.pageExecute(request).getBody();

            return new Result<>(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return new Result<>(CodeEnum.FAIL_100005); // 系统异常
        }
    }
}
